package cz.fimuni.pa165.backendderby.dao;

import cz.fimuni.pa165.backendderby.entities.Car;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;

/**
 *
 * @author Ondřej Myška
 */
@Repository
public class CarDAOImpl implements CarDAO {

    @PersistenceContext
    private EntityManager em;

    public void createCar(Car car) {
        
        if (car != null) {
            em.persist(car);
        }

    }

    public void remove(Car car) {
        
        if (car != null) {
            if (em.find(Car.class, car.getId()) == null) {
                return;
            }
            em.remove(em.merge(car));
        }
    }

    public boolean update(Car car) {
        
        if (car != null) {
            if (em.find(Car.class, car.getId()) == null) {
                return false;
            }
            em.persist(em.merge(car));
            return true;
        }
        return false;
    }

    public Car find(Long id) {
        
        if (id == null) {
            return null;
        }
        Car c = (Car) em.find(Car.class, id);
        return c;
    }

    public List<Car> getAllCars() {
        
        List<Car> l = em.createQuery("Select c FROM Car c").getResultList();
        return l;
    }

    public List<Car> getAllAvailibleCars() {
        Query q = em.createQuery("Select c FROM Car c WHERE c.available=:available");
        q.setParameter("available",true);
        List<Car> l =q.getResultList();
        return l;
    }

    public List<Car> getCar(String spz) {
        
        if (spz == null) {
            return null;
        }
        
        Query q = em.createQuery("Select c FROM Car c WHERE c.spz= :spz");
        q.setParameter("spz", spz);
        List<Car> c = q.getResultList();
        return c;
    }

    public List<Car> processQuery(String query) {
        Query q = em.createQuery(query);
        List<Car> c = q.getResultList();
        return c;
    }
  
}